package com.weight;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

public class WeightPreferences extends PreferenceActivity {
	
    private static final int CONTINUE = 0;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        boolean firstTime = pref.getBoolean("first_time",false);
        
        boolean optionsCall = getIntent().getBooleanExtra("optionscall", false);
        
        if(firstTime && !optionsCall ) {
        	 callRegistryAdd();
        }        

        addPreferencesFromResource(R.xml.weightpreferences);
    }
    
    

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		
		menu.add(0, CONTINUE , Menu.NONE, getString(R.string.menu_continue));
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		 super.onOptionsItemSelected(item); 
		 switch(item.getItemId()){
		 case CONTINUE:
			 if(checkFields()){
		     callRegistryAdd();
			 }
			 break;
		 }
		 
		 
		 return true;
	}

	private void callRegistryAdd() {
		Intent intent = new Intent(this,com.weight.LogEntry.class);
		 startActivity(intent);
	}

	private boolean checkFields() {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		boolean result = false;
		String name = pref.getString("name",null);
		String mail = pref.getString("mail", null);
		String recipientmail = pref.getString("recipientmail", null);
		android.util.Log.d("[PREFERENCES]", "name " + name + "mail" + mail + "recipientmail" + recipientmail );
		if(name!=null && mail !=null && recipientmail!=null) {
			result = true;
			SharedPreferences.Editor ed = pref.edit();
			ed.putBoolean("first_time", true);
			ed.commit();
		}
		return result;
	}
    
    
    
}